package com.googlecode.jsimplemarket.service;

import com.googlecode.jsimplemarket.model.Utilizator;
import com.googlecode.jsimplemarket.repository.GenericProperty;
import com.googlecode.jsimplemarket.repository.GenericRepository;
import com.googlecode.jsimplemarket.repository.GenericRestriction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Alexandru.Codescu
 */
@Service(value = "utilizatorService")
@Transactional(propagation = Propagation.REQUIRED)
public class UtilizatorService implements UserDetailsService {

    @Autowired
    private GenericRepository<Utilizator> utilizatorRepository;
    
    public Utilizator getById(long id) {
        return utilizatorRepository.getById(Utilizator.class, id);
    }

    @Override
    public UserDetails loadUserByUsername(String numeUtilizator) {
        GenericRestriction res = new GenericRestriction(new GenericProperty("numeUtilizator"), numeUtilizator);
        Utilizator user = utilizatorRepository.getSingleResult(Utilizator.class, res);

        if (user == null) {
            throw new UsernameNotFoundException(numeUtilizator + " not found");
        }

        return user;
    }
    
    public void save(Utilizator utilizator, boolean rehashuire) {
        if (rehashuire) {
            ShaPasswordEncoder shaPasswordEncoder = new ShaPasswordEncoder();
            String hashedPass = shaPasswordEncoder.encodePassword(
                    utilizator.getParola(), null);
            utilizator.setParola(hashedPass);
        }
        utilizatorRepository.save(utilizator);
    }
}
